package com.tre.jdevtemplateboot.web.interceptor;

import com.tre.jdevtemplateboot.common.constant.SysConstantToken;
import com.tre.jdevtemplateboot.common.dto.PropertiesConfig;
import com.tre.jdevtemplateboot.common.redis.IRedisTokenManagerService;
import com.tre.jdevtemplateboot.exception.business.SysInvalidTokenException;
import com.tre.jdevtemplateboot.exception.business.SysUnAuthenticatedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: JDev
 **/
@Component
public class JDevRequestHeadRedisInterceptor implements HandlerInterceptor {

    @Autowired
    private IRedisTokenManagerService tokenManagerService;

    @Autowired
    PropertiesConfig propertiesVO;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws SysInvalidTokenException, IOException {

        String headerJwtToken = HeadToken.getHeadToken(request, propertiesVO.getAuthHeaderKey(), propertiesVO.getAuthTypePrefix());
        if (!StringUtils.hasLength(headerJwtToken)) {
            throw new SysUnAuthenticatedException();
        }
        headerJwtToken = tokenManagerService.updateToken(headerJwtToken);
        response.setHeader(propertiesVO.getPreUserIssuer() + SysConstantToken.SUFFIX_USER_ISSUER, headerJwtToken);
        return true;
    }

}
